package cn.sinata.wanglin.neighbor.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.easemob.redpacketui.RedPacketConstant;
import com.easemob.redpacketui.utils.RedPacketUtil;
import com.easemob.redpacketui.widget.ChatRowRedPacket;
import com.easemob.redpacketui.widget.ChatRowRedPacketAck;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.util.PathUtil;
import com.xilada.xldutils.utils.PermissionManager;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import cn.sinata.wanglin.R;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.db.dao.GroupDao;
import cn.sinata.wanglin.db.dao.GroupUserDao;
import cn.sinata.wanglin.db.dao.UserDao;
import cn.sinata.wanglin.db.model.User;
import cn.sinata.wanglin.model.Group;
import cn.sinata.wanglin.neighbor.activity.ContextMenuActivity;
import cn.sinata.wanglin.neighbor.activity.GroupInfoActivity;
import cn.sinata.wanglin.neighbor.activity.ImageGridActivity;
import cn.sinata.wanglin.village.activity.AllUserInfoActivity;

public class ChatFragment extends EaseChatFragment implements EaseChatFragment.EaseChatFragmentHelper {

    //避免和基类定义的常量可能发生的冲突，常量从11开始定义
    private static final int ITEM_VIDEO = 11;
    private static final int ITEM_FILE = 12;
    private static final int ITEM_VOICE_CALL = 13;
    private static final int ITEM_VIDEO_CALL = 14;
    private static final int ITEM_READFIRE = 15;

    private static final int REQUEST_CODE_SELECT_VIDEO = 11;
    private static final int REQUEST_CODE_SELECT_FILE = 12;
    private static final int REQUEST_CODE_GROUP_DETAIL = 13;
    private static final int REQUEST_CODE_CONTEXT_MENU = 14;
    private static final int REQUEST_CODE_SEND_MONEY = 15;


    private static final int MESSAGE_TYPE_SENT_VOICE_CALL = 1;
    private static final int MESSAGE_TYPE_RECV_VOICE_CALL = 2;
    private static final int MESSAGE_TYPE_SENT_VIDEO_CALL = 3;
    private static final int MESSAGE_TYPE_RECV_VIDEO_CALL = 4;

    private static final int MESSAGE_TYPE_RECV_MONEY = 5;
    private static final int MESSAGE_TYPE_SEND_MONEY = 6;
    private static final int MESSAGE_TYPE_SEND_LUCKY = 7;
    private static final int MESSAGE_TYPE_RECV_LUCKY = 8;

    private static final int ITEM_RED_PACKET = 16;

//    private static final int REQUEST_CODE_SEND_RED_PACKET = 16;

    /**
     * 是否为环信小助手
     */
    private boolean isRobot;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void setUpView() {
        setChatFragmentListener(this);
        super.setUpView();
//        ((EaseEmojiconMenu)inputMenu.getEmojiconMenu()).addEmojiconGroup(EmojiconExampleGroupData.getData());
    }

    @Override
    protected void registerExtendMenuItem() {
        //demo这里不覆盖基类已经注册的item,item点击listener沿用基类的
        super.registerExtendMenuItem();
        //增加扩展item
        inputMenu.registerExtendMenuItem(R.string.attach_video, R.drawable.em_chat_video_selector, ITEM_VIDEO, extendMenuItemClickListener);
//        inputMenu.registerExtendMenuItem(R.string.attach_file, R.drawable.em_chat_file_selector, ITEM_FILE, extendMenuItemClickListener);
//        if(chatType == EaseConstant.CHATTYPE_SINGLE){
//            inputMenu.registerExtendMenuItem(R.string.attach_voice_call, R.drawable.em_chat_voice_call_selector, ITEM_VOICE_CALL, extendMenuItemClickListener);
//            inputMenu.registerExtendMenuItem(R.string.attach_video_call, R.drawable.em_chat_video_call_selector, ITEM_VIDEO_CALL, extendMenuItemClickListener);
////            // 阅后即焚开关菜单
////            inputMenu.registerExtendMenuItem(R.string.attach_read_fire, R.drawable.ease_read_fire, ITEM_READFIRE, extendMenuItemClickListener);
//        }

        //聊天室暂时不支持红包功能
        if (chatType != EaseConstant.CHATTYPE_CHATROOM) {
            inputMenu.registerExtendMenuItem(R.string.attach_red_packet, R.drawable.em_chat_red_packet_selector, ITEM_RED_PACKET, extendMenuItemClickListener);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("lzan13", "ChatFragment - onActivityResult - "+requestCode);
        if (resultCode == Constant.ResultCode_QUITE) {
            if (requestCode == REQUEST_CODE_GROUP_DETAIL) {
                getActivity().setResult(Constant.ResultCode_QUITE);
                getActivity().finish();
                return;
            }
        }

        if (resultCode == Constant.ResultCode_CANCEL_FRIEND) {
            getActivity().setResult(Constant.ResultCode_CANCEL_FRIEND);
            getActivity().finish();
            return;
        }
        if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
            switch (resultCode) {
            case ContextMenuActivity.RESULT_CODE_COPY: // 复制消息
                clipboard.setText(((EMTextMessageBody) contextMenuMessage.getBody()).getMessage());
                break;
            case ContextMenuActivity.RESULT_CODE_DELETE: // 删除消息
                conversation.removeMessage(contextMenuMessage.getMsgId());
                refreshUI();
                break;

            case ContextMenuActivity.RESULT_CODE_FORWARD: // 转发消息
//                if(chatType == EaseConstant.CHATTYPE_CHATROOM){
//                    Toast.makeText(getActivity(), R.string.chatroom_not_support_forward, 1).show();
//                    return;
//                }
//                Intent intent = new Intent(getActivity(), ForwardMessageActivity.class);
//                intent.putExtra("forward_msg_id", contextMenuMessage.getMsgId());
//                startActivity(intent);

                break;
            default:
                break;
            }
        }
        if(resultCode == Activity.RESULT_OK){
            switch (requestCode) {
            case REQUEST_CODE_SELECT_VIDEO: //发送选中的视频
                if (data != null) {
                    int duration = data.getIntExtra("dur", 0);
                    String videoPath = data.getStringExtra("path");
                    File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
                    try {
                        FileOutputStream fos = new FileOutputStream(file);
                        Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                        ThumbBitmap.compress(CompressFormat.JPEG, 100, fos);
                        fos.close();
                        sendVideoMessage(videoPath, file.getAbsolutePath(), duration);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case REQUEST_CODE_SELECT_FILE: //发送选中的文件
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        sendFileByUri(uri);
                    }
                }
                break;
            case REQUEST_CODE_SEND_MONEY:
                if (data != null) {
                    sendMessage(RedPacketUtil.createRPMessage(getActivity(), data, toChatUsername));
                }
                break;
            default:
                break;
            }
        }

    }

    /**
     * 刷新UI界面
     */
    public void refreshUI(){
        messageList.refresh();
    }

    /**
     * 为消息对象添加扩展字段
     * params message   需要处理的消息对象
     */
    @Override
    public void onSetMessageAttributes(EMMessage message) {

        String headUrl = SharedPreferencesUtils.getString(Constant.SP_HEADURL);
        String nick = SharedPreferencesUtils.getString(Constant.SP_NICKNAME);
        String userId = SharedPreferencesUtils.getString(Constant.SP_USERID);
        Utils.systemErr(message.getChatType());
        if (message.getChatType() == EMMessage.ChatType.GroupChat) {
            String toUser = toChatUsername;
            String account = SharedPreferencesUtils.getString(Constant.SP_IM_ACCOUNT);
            User user = GroupUserDao.getInstance(getContext()).getUser(toUser, account);
            Utils.systemErr("--user->"+user);
            if (user != null) {
                nick = user.getName();
            }
            Group group = GroupDao.getInstance(getContext()).getGroup(userId, toChatUsername);
            message.setAttribute("groupId", group.getId());
            message.setAttribute("groupImg", group.getGroupImg());
            message.setAttribute("groupName", group.getGroupName());
        }
        message.setAttribute("nick",nick);
        message.setAttribute("headUrl",headUrl);
    }

    @Override
    public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
        //设置自定义listview item提供者
        return new CustomChatRowProvider();
    }

    @Override
    public void onEnterToUserDetails(){
        if (toChatUsername == null) {
            return;
        }
//        User user = UserDao.getInstance(getContext()).getUser(toChatUsername);
//        if (user == null) {
//            return;
//        }

        Intent intent = new Intent(getActivity(), AllUserInfoActivity.class);
        intent.putExtra("friendID", toChatUsername);
        intent.putExtra("type", 1);
        startActivityForResult(intent,14);
    }

    @Override
    public void onEnterToChatDetails() {
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            String userId = SharedPreferencesUtils.getString(Constant.SP_USERID);
            Group group = GroupDao.getInstance(getContext()).getGroup(userId,toChatUsername);
            if (group == null) {
                Toast.makeText(getActivity(), R.string.gorup_not_found, Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(getActivity(), GroupInfoActivity.class);
            intent.putExtra("id", toChatUsername);
            intent.putExtra("type",1);
            intent.putExtra("name",group.getGroupName());
            startActivityForResult(intent, REQUEST_CODE_GROUP_DETAIL);
//        }else if(chatType == Constant.CHATTYPE_CHATROOM){
//        	startActivityForResult(new Intent(getActivity(), ChatRoomDetailsActivity.class).putExtra("roomId", toChatUsername), REQUEST_CODE_GROUP_DETAIL);
        }
    }

    @Override
    public void onAvatarClick(String username) {
        //头像点击事件
        if (username == null) {
            return;
        }
//        User user = UserDao.getInstance(getContext()).getUser(username);
//        if (user == null) {
//            return;
//        }
        int type = chatType == EaseConstant.CHATTYPE_GROUP?2:1;
        Intent intent = new Intent(getActivity(), AllUserInfoActivity.class);
        intent.putExtra("friendID", username);
        intent.putExtra("type", type);
        startActivityForResult(intent,14);
    }

    @Override
    public void onAvatarLongClick(String username) {

    }

    @Override
    public boolean onMessageBubbleClick(EMMessage message) {
        //消息框点击事件，demo这里不做覆盖，如需覆盖，return true
        if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)){
            RedPacketUtil.openRedPacket(getActivity(), chatType, message, toChatUsername, messageList);
            return true;
        }
        return false;
    }

    @Override
    public void onMessageBubbleLongClick(EMMessage message) {
        //消息框长按
        startActivityForResult((new Intent(getActivity(), ContextMenuActivity.class)).putExtra("message",message)
                        .putExtra("ischatroom", chatType == EaseConstant.CHATTYPE_CHATROOM),
                REQUEST_CODE_CONTEXT_MENU);
    }

    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
        switch (itemId) {
        case ITEM_VIDEO: //视频
            boolean hasP = PermissionManager.request(getActivity(), Manifest.permission.RECORD_AUDIO,"使用视频或音频设备",10);
            if (hasP) {
                Intent intent = new Intent(getActivity(), ImageGridActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
            } else {
                com.xilada.xldutils.utils.Toast.create(this).show("没有摄像头或音频设备使用权限！无法使用该功能");
            }
            break;
//        case ITEM_FILE: //一般文件
//            //demo这里是通过系统api选择文件，实际app中最好是做成qq那种选择发送文件
//            selectFileFromLocal();
//            break;
            case ITEM_RED_PACKET:
                RedPacketUtil.startRedPacketActivityForResult(this, chatType, toChatUsername, REQUEST_CODE_SEND_MONEY);
                break;
        default:
            break;
        }
        //不覆盖已有的点击事件
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions.length > 0) {
            SharedPreferencesUtils.save(permissions[0],false);
        }
    }

    /**
     * 选择文件
     */
    protected void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) { //19以后这个api不可用，demo这里简单处理成图库选择图片
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }

    /**
     * chat row provider
     *
     */
    private final class CustomChatRowProvider implements EaseCustomChatRowProvider {
        @Override
        public int getCustomChatRowTypeCount() {
            //音、视频通话发送、接收共4种
            return 4;
        }

        @Override
        public int getCustomChatRowType(EMMessage message) {
            if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {
                //发送红包消息
                return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_MONEY : MESSAGE_TYPE_SEND_MONEY;
            } else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {
                //领取红包消息
                return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_LUCKY : MESSAGE_TYPE_SEND_LUCKY;
            }
            return 0;
        }

        @Override
        public EaseChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {

            if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {//发送红包消息
                return new ChatRowRedPacket(getActivity(), message, position, adapter);
            } else if (message.getBooleanAttribute(RedPacketConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {//领取红包消息
                return new ChatRowRedPacketAck(getActivity(), message, position, adapter);
            }
            return null;
        }
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        for (EMMessage message : messages) {
            EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
            String action = cmdMsgBody.action();//获取自定义action
            if (action.equals(RedPacketConstant.REFRESH_GROUP_RED_PACKET_ACTION)){
                RedPacketUtil.receiveRedPacketAckMessage(message);
                messageList.refresh();
            }
        }
        super.onCmdMessageReceived(messages);
    }
}